<script setup lang="ts">
import { ref, onMounted } from "vue";
import {
  getStatisticsDashboard,
  getStatisticsTrends,
  getStatisticsAttackCategories,
  getStatisticsVulnerabilityDetails,
} from "../servers";
import { useECharts } from "@pureadmin/utils";
import { ElMessage, ElProgress } from "element-plus";

const props = defineProps<{
  task: string;
}>();

const dashboardData = ref<any>(null);
const trendsData = ref<any>(null);
const attackCategoriesData = ref<any>(null);
const vulnerabilityDetails = ref<any[]>([]);

// 攻击类别Top5列表
const attackCategoriesTop5 = ref<any[]>([]);

const loading = ref(false);

// 核心指标卡片数据
const metrics = ref([
  { title: "总测试", value: 0, color: "#409EFF" },
  { title: "威胁数量", value: 0, color: "#F56C6C" },
  { title: "安全评分", value: "0分", color: "#67C23A" },
  { title: "通过率", value: "0%", color: "#E6A23C" },
]);

// 趋势图表
const trendsChartRef = ref<HTMLDivElement>();
const trendsChart = useECharts(trendsChartRef);

// 严重等级分布饼图
const severityChartRef = ref<HTMLDivElement>();
const severityChart = useECharts(severityChartRef);

// 攻击类别饼图（如果有数据）
const attackChartRef = ref<HTMLDivElement>();
const attackChart = useECharts(attackChartRef);

// 威胁详情表格列
const vulnerabilityColumns = [
  { prop: "severity", label: "严重度", minWidth: 100 },
  { prop: "scenario_name", label: "场景名称", minWidth: 200 },
  { prop: "target_url", label: "目标URL", minWidth: 250 },
  { prop: "found_at", label: "发现时间", minWidth: 180 },
  { prop: "confidence", label: "置信度", minWidth: 100 },
  {
    prop: "action",
    label: "操作",
    fixed: "right",
    width: 100,
    slot: "action",
  },
];

const fetchData = async () => {
  loading.value = true;
  try {
    const [dashboard, trends, categories, vulnerabilities] = await Promise.all([
      getStatisticsDashboard(),
      getStatisticsTrends(),
      getStatisticsAttackCategories(),
      getStatisticsVulnerabilityDetails({ page_size: 10 }),
    ]);

    dashboardData.value = dashboard.data;
    trendsData.value = trends.data;
    attackCategoriesData.value = categories.data;
    vulnerabilityDetails.value = vulnerabilities.data?.vulnerabilities || [];

    // 计算攻击类别Top5
    if (categories.data?.categories) {
      const categoriesList = categories.data.categories || [];
      attackCategoriesTop5.value = categoriesList
        .map((item: any) => ({
          category: item.category,
          categoryDisplay: getCategoryDisplayName(item.category),
          vulnerabilities: Number(item.vulnerabilities || 0),
          totalTests: Number(item.total_tests || 0),
          vulnerabilityRate: Number(item.vulnerability_rate || 0),
        }))
        .filter((item: any) => item.vulnerabilities > 0)
        .sort((a: any, b: any) => b.vulnerabilities - a.vulnerabilities)
        .slice(0, 5);
    } else {
      attackCategoriesTop5.value = [];
    }

    // 计算核心指标 - 根据真实返回数据结构
    const overview = dashboard.data?.overview || {};
    metrics.value = [
      {
        title: "总测试",
        value: overview.total_tests || 0,
        color: "#409EFF",
      },
      {
        title: "威胁数量",
        value: overview.vulnerabilities_found || 0,
        color: "#F56C6C",
      },
      {
        title: "安全评分",
        value: `${overview.security_score || 0}分`,
        color: "#67C23A",
      },
      {
        title: "通过率",
        value: `${(overview.pass_rate || 0).toFixed(1)}%`,
        color: "#E6A23C",
      },
    ];

    // 绘制图表
    drawTrendsChart();
    drawSeverityChart();
    drawAttackChart();
  } catch (error) {
    console.error("获取仪表盘数据失败", error);
    ElMessage.error("获取仪表盘数据失败");
  } finally {
    loading.value = false;
  }
};

// 绘制趋势图表
const drawTrendsChart = () => {
  if (!trendsData.value?.daily_trends) return;

  const dailyTrends = trendsData.value.daily_trends;
  const dates = dailyTrends.map((item: any) => item.date);
  const vulnerabilities = dailyTrends.map((item: any) => item.vulnerabilities);
  const vulnerabilityRate = dailyTrends.map(
    (item: any) => item.vulnerability_rate
  );

  trendsChart.setOptions({
    title: {
      text: "风险趋势分析",
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["威胁数量数", "威胁率"],
      bottom: 0,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: dates,
      boundaryGap: false,
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: [
      {
        type: "value",
        name: "威胁数",
        position: "left",
      },
      {
        type: "value",
        name: "威胁率(%)",
        position: "right",
      },
    ],
    series: [
      {
        name: "威胁数量数",
        type: "line",
        data: vulnerabilities,
        smooth: true,
        itemStyle: { color: "#F56C6C" },
      },
      {
        name: "威胁率",
        type: "line",
        yAxisIndex: 1,
        data: vulnerabilityRate,
        smooth: true,
        itemStyle: { color: "#409EFF" },
      },
    ],
  });
};

// 绘制严重等级分布饼图 - 根据真实返回数据
const drawSeverityChart = () => {
  if (!dashboardData.value?.severity_distribution) return;

  const severityDist = dashboardData.value.severity_distribution;
  const data = [
    {
      name: "严重",
      value: Number(severityDist.critical?.vulnerable || 0),
      total: Number(severityDist.critical?.total || 0),
    },
    {
      name: "高危",
      value: Number(severityDist.high?.vulnerable || 0),
      total: Number(severityDist.high?.total || 0),
    },
    {
      name: "中危",
      value: Number(severityDist.medium?.vulnerable || 0),
      total: Number(severityDist.medium?.total || 0),
    },
    {
      name: "低危",
      value: Number(severityDist.low?.vulnerable || 0),
      total: Number(severityDist.low?.total || 0),
    },
  ].filter((item) => item.value > 0); // 只显示有威胁的等级

  if (data.length === 0) return;

  severityChart.setOptions({
    title: {
      text: "严重等级分布",
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "item",
      formatter: (params: any) => {
        const dataItem = params.data;
        return `${params.name}<br/>有威胁: ${dataItem.value}个<br/>总数: ${dataItem.total}个<br/>占比: ${params.percent}%`;
      },
    },
    legend: {
      orient: "vertical",
      left: "left",
      bottom: 0,
      data: data.map((item) => item.name),
    },
    series: [
      {
        name: "严重等级",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: "{b}\n{d}%",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        data: data.map((item) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color:
              item.name === "严重"
                ? "#ff4d4f"
                : item.name === "高危"
                ? "#ff7a45"
                : item.name === "中危"
                ? "#faad14"
                : "#52c41a",
          },
        })),
      },
    ],
  });
};

// 攻击类别中文名称映射
const getCategoryDisplayName = (category: string) => {
  const categoryMap: Record<string, string> = {
    apache_commons: "Apache Commons",
    api_security: "API安全",
    apt_technique: "APT技术",
    authentication: "身份认证",
    cloud_native: "云原生",
    collaboration: "协作平台",
    database: "数据库",
    infrastructure: "基础设施",
    web_attack: "Web攻击",
    web_framework: "Web框架",
  };
  return categoryMap[category] || category;
};

// 绘制攻击类别饼图（如果有数据）
const drawAttackChart = () => {
  if (!attackCategoriesData.value?.categories) return;

  const categories = attackCategoriesData.value.categories || [];

  // 按漏洞数量排序，取Top5
  const sortedCategories = categories
    .map((item: any) => ({
      name: getCategoryDisplayName(item.category),
      value: Number(item.vulnerabilities || 0),
      total: Number(item.total_tests || 0),
      rate: Number(item.vulnerability_rate || 0),
      originalCategory: item.category,
    }))
    .filter((item: any) => item.value > 0) // 只显示有漏洞的类别
    .sort((a: any, b: any) => b.value - a.value)
    .slice(0, 5); // 取Top5

  if (sortedCategories.length === 0) return;

  attackChart.setOptions({
    title: {
      text: "攻击类别Top5",
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "item",
      formatter: (params: any) => {
        const dataItem = params.data;
        return `${params.name}<br/>有威胁: ${dataItem.value}个<br/>总数: ${dataItem.total}个<br/>威胁率: ${dataItem.rate}%<br/>占比: ${params.percent}%`;
      },
    },
    legend: {
      orient: "vertical",
      left: "left",
      bottom: 0,
      data: sortedCategories.map((item: any) => item.name),
    },
    series: [
      {
        name: "攻击类别",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: "{b}\n{d}%",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        data: sortedCategories.map((item: any, index: number) => ({
          value: item.value,
          name: item.name,
          total: item.total,
          rate: item.rate,
          itemStyle: {
            color: ["#ff4d4f", "#ff7a45", "#faad14", "#52c41a", "#409EFF"][
              index % 5
            ],
          },
        })),
      },
    ],
  });
};

// 获取严重度标签类型
const getSeverityType = (
  severity: string
): "success" | "warning" | "info" | "danger" => {
  const severityMap: Record<string, "success" | "warning" | "info" | "danger"> =
    {
      critical: "danger",
      high: "danger",
      medium: "warning",
      low: "info",
    };
  return severityMap[severity?.toLowerCase()] || "info";
};

const getSeverityText = (severity: string) => {
  const severityMap: Record<string, string> = {
    critical: "严重",
    high: "高危",
    medium: "中危",
    low: "低危",
  };
  return severityMap[severity?.toLowerCase()] || severity;
};

// 获取攻击类别进度条颜色
const getCategoryProgressColor = (index: number) => {
  const colors = ["#ff4d4f", "#ff7a45", "#faad14", "#52c41a", "#409EFF"];
  return colors[index % colors.length];
};

// 查看威胁详情
const handleViewDetail = (row: any) => {
  ElMessage.info(`查看威胁详情: ${row.scenario_name}`);
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="dashboard-container">
    <!-- 核心指标卡片 -->
    <el-row :gutter="20" style="margin-bottom: 20px">
      <el-col :span="6" v-for="(metric, index) in metrics" :key="index">
        <el-card shadow="hover" class="metric-card">
          <div class="metric-content">
            <div class="metric-info">
              <div class="metric-title">{{ metric.title }}</div>
              <div class="metric-value" :style="{ color: metric.color }">
                {{ metric.value }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势分析图表 -->
    <el-row :gutter="20" style="margin-bottom: 20px">
      <el-col :span="24">
        <el-card shadow="hover">
          <div ref="trendsChartRef" style="height: 350px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 攻击类别Top5 -->
    <!-- <el-row :gutter="20" style="margin-bottom: 20px">

    </el-row> -->

    <!-- 严重等级分布和最新威胁 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover">
          <div ref="severityChartRef" style="height: 350px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-col :span="24">
          <el-card shadow="hover">
            <template #header>
              <div
                style="font-weight: bold; font-size: 18px; margin-bottom: 10px"
              >
                攻击类别Top5
              </div>
            </template>
            <div class="attack-categories-list">
              <div
                v-for="(item, index) in attackCategoriesTop5"
                :key="index"
                class="category-item"
              >
                <div class="category-info">
                  <span class="category-rank">{{ index + 1 }}.</span>
                  <span class="category-name">{{ item.categoryDisplay }}</span>
                  <span class="category-count"
                    >({{ item.vulnerabilities }}次)</span
                  >
                </div>
                <div class="category-progress">
                  <el-progress
                    :percentage="item.vulnerabilityRate"
                    :color="getCategoryProgressColor(index)"
                    :stroke-width="12"
                  />
                </div>
                <!-- <div class="category-rate">{{ item.vulnerabilityRate }}%</div> -->
              </div>
              <el-empty
                v-if="!loading && attackCategoriesTop5.length === 0"
                description="暂无数据"
                :image-size="80"
              />
            </div>
          </el-card>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
}

.metric-card {
  .metric-content {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .metric-info {
    width: 100%;
    text-align: center;
  }

  .metric-title {
    font-size: 18px;
    font-weight: bold;
    color: #909399;
    margin-bottom: 12px;
  }

  .metric-value {
    font-size: 32px;
    font-weight: bold;
    line-height: 1;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;

  span {
    font-size: 16px;
    font-weight: bold;
  }
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  .el-table__cell {
    padding: 12px 0;
  }
}

.attack-categories-list {
  .category-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 12px 0;
    border-bottom: 1px solid #ebeef5;

    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
    }

    .category-info {
      display: flex;
      align-items: center;
      width: 200px;
      flex-shrink: 0;

      .category-rank {
        width: 24px;
        font-weight: bold;
        color: #909399;
        font-size: 14px;
      }

      .category-name {
        flex: 1;
        font-size: 14px;
        color: #606266;
        font-weight: 500;
      }

      .category-count {
        font-size: 12px;
        color: #909399;
        margin-left: 8px;
      }
    }

    .category-progress {
      flex: 1;
      margin: 0 20px;
    }

    .category-rate {
      width: 60px;
      text-align: right;
      font-size: 14px;
      color: #606266;
      font-weight: 500;
    }
  }
}
</style>
